package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.consts.SrbConsts;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserIntegral;
import com.atguigu.srb.core.pojo.entity.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.entity.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.entity.vo.BorrowerVO;
import com.atguigu.srb.core.service.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2023-05-26
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    UserInfoService userInfoService;
    @Resource
    DictService dictService;
    @Resource
    BorrowerAttachService borrowerAttachService;
    @Resource
    UserIntegralService userIntegralService;
    @Override
    public void saveBorrowerVO(BorrowerVO borrowerVO, String token) {
        Long userId = JwtUtils.getUserId(token);
        //1、保存借款人数据到数据库
        Borrower borrower = new Borrower();
        //属性名和类型 都相同时才可以进行属性值拷贝
        BeanUtils.copyProperties(borrowerVO , borrower);
        //设置前端没有传入的属性值给borrower
        //borrower中需要保存 会员的数据(user_info表中的)
        UserInfo userInfo = userInfoService.getById(userId);
        borrower.setUserId(userId);
        borrower.setIdCard(userInfo.getIdCard());

        borrower.setMobile(userInfo.getMobile());
        borrower.setName(userInfo.getName());
        borrower.setStatus(1);
        this.save(borrower);

        //2、保存借款人附件数据到数据库
        List<BorrowerAttach> borrowerAttaches = borrowerVO.getBorrowerAttaches();
        if(!CollectionUtils.isEmpty(borrowerAttaches)){
            borrowerAttaches.forEach(borrowerAttach -> borrowerAttach.setBorrowerId(borrower.getId()));
            borrowerAttachService.saveBatch(borrowerAttaches);
        }


    }

    @Override
    public Integer getStatus(String token) {
        Long userId = JwtUtils.getUserId(token);
        Borrower borrower = this.getOne(Wrappers.lambdaQuery(Borrower.class)
                .eq(Borrower::getUserId, userId)
                .select(Borrower::getStatus));
        return borrower==null?0:borrower.getStatus();
    }

    @Override
    public Page<Borrower> getBorrowerPage(Integer pageNum, Integer pageSize, String key) {
        Page<Borrower> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Borrower> queryWrapper = Wrappers.lambdaQuery(Borrower.class);
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.like(Borrower::getName , key)
                    .or()
                    .like(Borrower::getIdCard , key)
                    .or()
                    .like(Borrower::getMobile,key);
        }
        //使用QueryWrapper的page方法时，它查询到的数据集合会自动设置给传入的page对象的records属性接收
        this.page(page,queryWrapper);
        //对查询到的Borrower集合数据进行处理，每个borrower对象的marry和status转为前端需要的字符串
        page.getRecords().forEach(borrower -> {
            Integer status = borrower.getStatus();
            Boolean marry = borrower.getMarry();
            //为了让borrower携带页面需要的处理过的数据，可以对bean进行扩展/也可以自定义vo类
            borrower.getParams().put("marry",marry?"是":"否");
            String statusStr = getStatusString(status);
            borrower.getParams().put("status", statusStr);
        });

        return page;
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailById(String id) {
        Borrower borrower = this.getById(id);
        List<BorrowerAttach> borrowerAttaches = borrowerAttachService.list(Wrappers.lambdaQuery(BorrowerAttach.class)
                .eq(BorrowerAttach::getBorrowerId, id));

        //将以上的数据封装为BorrowerDetailVO
        BorrowerDetailVO vo = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower,vo);
        //设置vo的params参数:
        // marry 是   ， status 待审核 , sex  男, education 研究生
        // industry 技师,  returnSource 工资 ,income 3000~5000  ， contactsRelation 兄弟
        vo.getParams().put("marry",borrower.getMarry()?"是":"否");
        vo.getParams().put("status",getStatusString(borrower.getStatus()));
        vo.getParams().put("sex",borrower.getSex()==0?"女":"男");
        //数据字典value值 可以到数据字典表中查询对应的标题
        // 查询education下的value值为borrower的value值的  数据字典
        String education = dictService.selectDictNameByDictCodeAndValue(SrbConsts.DICT_CODE_EDUCATION,
                borrower.getEducation());
        vo.getParams().put("education",education);
        String industry = dictService.selectDictNameByDictCodeAndValue(SrbConsts.DICT_CODE_INDUSTRY,
                borrower.getIndustry());
        vo.getParams().put("industry",industry);
        String returnSource = dictService.selectDictNameByDictCodeAndValue(SrbConsts.DICT_CODE_RETURN_SOURCE,
                borrower.getReturnSource());
        vo.getParams().put("returnSource",returnSource);
        String income = dictService.selectDictNameByDictCodeAndValue(SrbConsts.DICT_CODE_INCOME,
                borrower.getIncome());
        vo.getParams().put("income",income);
        String contactsRelation = dictService.selectDictNameByDictCodeAndValue(SrbConsts.DICT_CODE_RELATION,
                borrower.getContactsRelation());
        vo.getParams().put("contactsRelation",contactsRelation);

        //附件设置给vo
        vo.setBorrowerAttaches(borrowerAttaches);
        return vo;
    }
    //审批业务方法
    @Override
    public void borrowerApproval(BorrowerApprovalVO borrowerApprovalVO) {
        Integer status = borrowerApprovalVO.getStatus();
        //借款人id
        String borrowerId = borrowerApprovalVO.getBorrowerId();
        //获取借款人信息
        Borrower borrower = this.getById(borrowerId);
        UserInfo userInfo = userInfoService.getById(borrower.getUserId());
        //审批不通过：只需要更新userInfo和borrower表中的审批状态即可
        //审批通过： 除了更新userInfo和borrower的审批状态，还需要将积分保存到表中
        if(status==2){
            //更新积分
            Integer infoIntegral = borrowerApprovalVO.getInfoIntegral();
            Boolean isCarOk = borrowerApprovalVO.getIsCarOk();
            Boolean isIdCardOk = borrowerApprovalVO.getIsIdCardOk();
            Boolean isHouseOk = borrowerApprovalVO.getIsHouseOk();
            //总积分变量
            Integer integral = infoIntegral;
            //保存积分明细：每个单独保存
            List<UserIntegral> userIntegrals = new ArrayList<>();
            UserIntegral userInfoIntegral = new UserIntegral();
            userInfoIntegral.setUserId(borrower.getUserId());
            userInfoIntegral.setIntegral(infoIntegral);
            userInfoIntegral.setContent("基本信息积分");
            userIntegrals.add(userInfoIntegral);
            //车辆信息积分
            if(isCarOk){
                UserIntegral carIntegral = new UserIntegral();
                carIntegral.setUserId(borrower.getUserId());
                carIntegral.setIntegral(60);
                carIntegral.setContent("车辆信息积分");
                userIntegrals.add(carIntegral);

                integral+=60;
            }
            //身份证信息积分
            if(isIdCardOk){
                UserIntegral idCardIntegral = new UserIntegral();
                idCardIntegral.setUserId(borrower.getUserId());
                idCardIntegral.setIntegral(30);
                idCardIntegral.setContent("身份证信息积分");
                userIntegrals.add(idCardIntegral);
                integral+=30;

            }
            //房产证信息积分
            if(isHouseOk){
                UserIntegral houseIntegral = new UserIntegral();
                houseIntegral.setUserId(borrower.getUserId());
                houseIntegral.setIntegral(100);
                houseIntegral.setContent("房产证信息积分");
                userIntegrals.add(houseIntegral);
                integral+=100;
            }
            userIntegralService.saveBatch(userIntegrals);
            //累加积分
            userInfo.setIntegral(integral+userInfo.getIntegral());

        }

        //更新borrower的审批状态
        borrower.setStatus(status);
        this.updateById(borrower);
        //更新user_info会员的 审批状态
        userInfo.setBorrowAuthStatus(status);
        userInfoService.updateById(userInfo);

    }

    private String getStatusString(Integer status) {
        //（0：未认证，1：认证中， 2：认证通过， -1：认证失败）
        String statusStr;
        switch (status){
            case 0:
                statusStr = "未认证";
                break;
            case 1:
                statusStr = "认证中";
                break;
            case 2:
                statusStr = "认证通过";
                break;
            default:
                statusStr = "认证失败";
                break;
        }
        return statusStr;
    }
}
